package com.scilvet.reportcomposer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.scilvet.reportcomposer.exception.FileException;

public class ConfigurationManager {

	public static final String REPORT_DIRECTORY = "reportDirectory";
	public static final String OUTPUT_DIRECTORY = "outputDirectory";
	
	private static final String CONFIGURATION_FILE = "resources/configuration.properties";
	private static final String REPORT_DIRECTORY_DEFAULT_VALUE = "resources/report/";
	private static final String OUTPUT_DIRECTORY_DEFAULT_VALUE = "resources/output/";
	
	private static Properties configuration = null;
	
	private static Logger logger = Logger.getLogger(ConfigurationManager.class);
	
	public ConfigurationManager() throws FileException {
		
		if (configuration == null) {
			configuration = new Properties();
		}
		
		File configurationFile = new File(CONFIGURATION_FILE);
		
		try {
			if (!configurationFile.exists()) {
				configuration = fallbackConfiguration();
				configuration.store(new FileOutputStream(configurationFile), "Configuration File");
			} else {
				configuration.load(new FileInputStream(configurationFile));
			}
		} catch(IOException e) {
			logger.error(e.getMessage());
			throw new FileException("IO error during configuration manager setup", e);
		}
		
	}
	
	private Properties fallbackConfiguration() {
		Properties fallback = new Properties();
		fallback.put(REPORT_DIRECTORY, REPORT_DIRECTORY_DEFAULT_VALUE);
		fallback.put(OUTPUT_DIRECTORY, OUTPUT_DIRECTORY_DEFAULT_VALUE);
		
		return fallback;
	}
	
	public String getProperty(String key) {
		return configuration.getProperty(key);
	}
}
